package com.xperblueray.stepbystep.listener;

import com.xperblueray.stepbystep.model.SysDict;
import com.xperblueray.stepbystep.service.SysDictService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.List;

import static com.xperblueray.stepbystep.constant.Constant.ALL_ATTR;

@WebListener
public class SysDictListener implements ServletContextListener {
    Logger logger = LogManager.getLogger(this.getClass());

    @Resource
    private SysDictService sysDictService;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // 查询数据库所有属性
        List<SysDict> list = sysDictService.findAll();
        // 清除缓存中所有属性
        redisTemplate.delete(ALL_ATTR);
        // 将数据放到redis缓存中
        redisTemplate.opsForList().leftPushAll(ALL_ATTR, list);
        List<SysDict> queryUserList = redisTemplate.opsForList().range(ALL_ATTR, 0, -1);
        logger.info("缓存中目前的用户数有：" + queryUserList.size() + "人");
        logger.info("ServletContext 上下文初始化");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        logger.info("ServletContext上下文销毁");
    }
}
